﻿using MySql.Data.MySqlClient;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApp1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
          
        }

        private void btnInsert_Click(object sender, EventArgs e)
        {
            Form2 form2 = new Form2(new ConTactPerson(), 1);
            form2.ShowDialog();
            this.btnSearch_Click(sender, e);
        }

        private void btnSearch_Click(object sender, EventArgs e)
        {
            string sqlStr = "select * from contact_person";
            DataSet ds = MysqlHelper.ExeSqlQuery(sqlStr);
            if(ds!=null && ds.Tables.Count > 0)
            {
                dataGridView1.DataSource = ds.Tables[0];
            }

        }

        private void btnDelete_Click(object sender, EventArgs e)
        {
            DataGridViewRow dr = dataGridView1.CurrentRow;
            if (dr == null)
            {
                MessageBox.Show("请选择要修改的数据");
                return;
            }
            string sqlStr = "delete from contact_person where id=@id";
            MySqlParameter para = new MySqlParameter("@id",dr.Cells["ID"].Value);
            if(MysqlHelper.ExeSql(sqlStr, para))
            {
                MessageBox.Show("删除成功");
            }
            else
            {
                MessageBox.Show("删除失败");
            }
            this.btnSearch_Click(sender, e);
        }

        private void btnUpdate_Click(object sender, EventArgs e)
        {
            DataGridViewRow dr = dataGridView1.CurrentRow;
            if (dr == null)
            {
                MessageBox.Show("请选择要修改的数据");
                return;
            }
            ConTactPerson conTactPerson = new ConTactPerson();
            conTactPerson.id = Dr2Int(dr.Cells["ID"].Value);
            conTactPerson.name =Dr2Str( dr.Cells["Name1"].Value);
            conTactPerson.phone= Dr2Str(dr.Cells["phone"].Value);
            conTactPerson.address = Dr2Str(dr.Cells["address"].Value);
            Form2 form2 = new Form2(conTactPerson,0);
            form2.ShowDialog();
           

        }

        public string Dr2Str(Object o)
        {
            if (o!= null)
            {
                return o.ToString();
            }
            return string.Empty;
        }

        public int Dr2Int(Object o)
        {
            int result = 0;
            if (o != null)
            {
                int.TryParse(o.ToString(), out result);
            }
            return result;
        }

        private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {

        }
    }
}
